package com.example.musicplayer.service;

import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;


import com.example.musicplayer.R;
import com.example.musicplayer.entity.Music;
import com.example.musicplayer.util.MusicNotification;
import com.example.musicplayer.util.SingletonMediaPlayer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author 张强
 */
public class MusicService extends Service {
    // 播放器模式列表
    private String[] PLAY_MODE_LIST = {"LIST", "SINGLE", "RANDOM"};
    // 当前播放器模式指针
    private int mPlayModeIndex = 0;


    private String mCurrentPlayMode;
    private static MusicBinder mMusicBinder;
    private MediaPlayer mMediaPlayer;
    private List<Music> mMusics; // 歌曲集合
    private List<Music> mLocalMusics; // 本地音乐
    private Music mMusic; // 存储当前正在播放的音乐

    // 想要查询的列名称
    private String[] mProjection = new String[]{
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.DATA
    };
    private int mCurrentIndex = -1; // 当前播放音乐索引

    // 通知栏
    private MusicNotification musicNotification;

    /**
     * Provide Music Service
     */
    public class MusicBinder extends Binder {
        /**
         * Start play music
         */
        public void startMusic() {
            if (mMediaPlayer != null) {
                mMediaPlayer.start();
            }
        }

        /**
         * stop play music
         */
        public void pauseMusic() {
            if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                mMediaPlayer.pause();
            }
        }

        /**
         * skip to next song
         */
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public void skipToNextSong() {
            if (mCurrentPlayMode.equals("LIST") || mCurrentPlayMode.equals("SINGLE")) { // LIST和SINGLE模式的下一首都是列表的下一首
                if (mMediaPlayer != null) {
                    mCurrentIndex++;
                    // 播放到最后一首歌时，自动回到第一首歌（顺序播放时）
                    if (mCurrentIndex > mMusics.size() - 1) {
                        mCurrentIndex = 0;
                    }
                    playMusic(mCurrentIndex);
                }
            } else if (mCurrentPlayMode.equals("RANDOM")) {  // 随机播放的下一首，是列表中的随机一首。
                mCurrentIndex = ThreadLocalRandom.current().nextInt(0, mMusics.size());
                Log.i("==================", "正在播放第" + mCurrentIndex + "首歌。");
                playMusic(mCurrentIndex);
            }
        }

        /**
         * skip to previous song
         */
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public void skipToPreviousSong() {
            if (mCurrentPlayMode.equals("LIST") || mCurrentPlayMode.equals("SINGLE")) {
                if (mMediaPlayer != null) {
                    mCurrentIndex--;
                    // 如果正在播放的是第一首歌，则自动跳到最后一首歌（顺序播放时）
                    if (mCurrentIndex < 0) {
                        mCurrentIndex = mMusics.size() - 1;
                    }
                    playMusic(mCurrentIndex);
                }
            } else if (mCurrentPlayMode.equals("RANDOM")) {  // 随机播放的上一首，是列表中的随机一首。
                mCurrentIndex = ThreadLocalRandom.current().nextInt(0, mMusics.size());
                Log.i("==================", "正在播放第" + mCurrentIndex + "首歌。");
                playMusic(mCurrentIndex);
            }
        }

        /**
         * 改变播放器模式
         */
        public void changePlayMode() {
            mPlayModeIndex++;
            if (mPlayModeIndex == PLAY_MODE_LIST.length) {
                mPlayModeIndex = 0;
            }
            mCurrentPlayMode = PLAY_MODE_LIST[mPlayModeIndex];
        }

        /**
         * 获取当前播放模式
         */
        public String getCurrentPlayMode() {
            return mCurrentPlayMode;
        }


        /**
         * get music list
         */
        public List<Music> getMusicList() {
            if (mMusics != null) {
                return mMusics;
            } else {
                return null;
            }
        }


        public List<Music> getLocalMusicList() {
            if (mLocalMusics != null) {
                return mLocalMusics;
            } else {
                return null;
            }
        }

        /**
         * 歌曲是否正在播放
         */
        public boolean isPlaying() {
            if (mMediaPlayer != null) {
                return mMediaPlayer.isPlaying();
            } else {
                return false;
            }
        }

        /**
         * 返回当前正在播放的音乐
         */
        public Music getCurrentMusic() {
            if (mMusic != null) {
                return mMusic;
            } else {
                return null;
            }
        }

        public void setCurrentMusicList(List<Music> musicList, int index) {
            mMusics = musicList;
            mCurrentIndex = index;
            playMusic(mCurrentIndex);
        }

        @RequiresApi(api = Build.VERSION_CODES.O)
        public void updateNotification(int notificationId) {
            if (mMusics.size() == 0) {
                return;
            }
            musicNotification.updateNotification(notificationId);
        }

        @RequiresApi(api = Build.VERSION_CODES.O)
        public void createNotification() {
            if (mMusics.size() == 0) {
                return;
            }
            musicNotification.createNotification();
        }

        /**
         * 获取MusicNotification对象
         *
         * @return 返回一个MusicNotification对象
         */
        public MusicNotification getMusicNotification() {
            return musicNotification;
        }
    }

    public static MusicBinder getMusicService() {
        while (true) {
            if (mMusicBinder != null) {
                return mMusicBinder;
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mMusicBinder;
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onCreate() {
        super.onCreate();
        musicNotification = new MusicNotification(this);
        initMusicResource();
        mMediaPlayer = SingletonMediaPlayer.getMediaPlayer();
        mMusicBinder = new MusicBinder();
        mCurrentPlayMode = PLAY_MODE_LIST[mPlayModeIndex];
        if (mCurrentIndex == -1 && mMusics.size() > 0) {
            mCurrentIndex++;
            preparePlayMusic(mCurrentIndex);
            Log.i("===========", "当前歌曲" + mCurrentIndex);
        }
        if (mMusics.size() == 0) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) getDrawable(R.drawable.album);
            assert bitmapDrawable != null;
            Bitmap bitmap = bitmapDrawable.getBitmap();
            mMusic = new Music("0", "pp音乐", "想听的都有", null, bitmap);
            mMusics.add(mMusic);
        }
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onCompletion(MediaPlayer mp) {
                // 根据不同播放模式，设置下一首音乐
                switch (mCurrentPlayMode) {
                    case "LIST":
                        mCurrentIndex++;
                        if (mCurrentIndex > mMusics.size() - 1) {
                            mCurrentIndex = 0;
                        }
                        playMusic(mCurrentIndex);
                        break;
                    case "SINGLE":
                        playMusic(mCurrentIndex);
                        break;
                    case "RANDOM":
                        mCurrentIndex = ThreadLocalRandom.current().nextInt(0, mMusics.size());
                        Log.i("==================", "正在播放第" + mCurrentIndex + "首歌。");
                        playMusic(mCurrentIndex);
                        break;
                }

            }
        });

    }

    /**
     * initial music resource.
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void initMusicResource() {
        Bitmap bitmap;
        mMusics = new ArrayList<>();
        Cursor cursor = getContentResolver().
                query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mProjection, null, null);
        assert cursor != null;
        while (cursor.moveToNext()) {
            String id = cursor.getString((cursor.getColumnIndex(MediaStore.Audio.Media._ID)));
            String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));

            // ======== 获取专辑封面(begin) ===================//
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            try {
                retriever.setDataSource(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
            } catch (Exception e) {
                e.printStackTrace();
            }

            byte[] data = retriever.getEmbeddedPicture();
            if (data != null) {
                bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            } else {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) getDrawable(R.drawable.album);
                assert bitmapDrawable != null;
                bitmap = bitmapDrawable.getBitmap();
            }
            mMusics.add(new Music(id, name, artist, path, bitmap));
            Log.i("===========", "MusicListSize" + mMusics.size());
            //========= 获取专辑封面(end) ===================//

        }
        cursor.close();
        mLocalMusics = mMusics;
        Toast.makeText(this, "歌曲加载完成", Toast.LENGTH_SHORT).show();
    }

    /**
     * 准备音乐播放资源
     *
     * @param index 正在准备的音乐播放资源的索引
     * @return 音乐准备是否成功，成功返回true，失败返回false。
     */
    private boolean preparePlayMusic(int index) {
        mMusic = mMusics.get(index);  // 获取当前音乐
        mMediaPlayer.reset();         // 重置mediaplayer对象
        try {
            if (mMusic.getPath() != null) {
                mMediaPlayer.setDataSource(mMusic.getPath());
                Log.i("==========", "当前音乐" + mMusic.getName());
                mMediaPlayer.prepare(); // 准备播放
            }
            return true;
        } catch (IOException e) {
            Toast.makeText(MusicService.this, "找不到资源。", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 音乐准备完毕后开始播放
     * @param index 当前音乐资源索引
     */
    private void playMusic(int index) {
        if (preparePlayMusic(index)) {
            mMediaPlayer.start();
        } else {
            Toast.makeText(this, "音乐加载失败！", Toast.LENGTH_SHORT).show();
        }
    }


}
